package com.sikao.app.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.Poi;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.DefaultSliderView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.sikao.app.R;
import com.sikao.app.adapter.PurchaseAdapter;
import com.sikao.app.adapter.SupplyAdapter;
import com.sikao.app.app.MyApplication;
import com.sikao.app.bean.Banner;
import com.sikao.app.bean.GetListSubmitBean;
import com.sikao.app.bean.MallBean;
import com.sikao.app.bean.TenderBean;
import com.sikao.app.dao.BannerModel;
import com.sikao.app.dao.MallListModel;
import com.sikao.app.dao.TenderListModel;
import com.sikao.app.fragment.base.BaseFragment;
import com.sikao.app.net.HttpApi;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.service.LocationService;
import com.sikao.app.ui.CompanyApplyActivity;
import com.sikao.app.ui.CompanyAreaActivity;
import com.sikao.app.ui.CompanyPerspectiveActivity;
import com.sikao.app.ui.EntrustsActivity;
import com.sikao.app.ui.FirstActivity;
import com.sikao.app.ui.GroupBuyActivity;
import com.sikao.app.ui.HotInformationActivity;
import com.sikao.app.ui.LatestQuotationActivity;
import com.sikao.app.ui.LoginActivity;
import com.sikao.app.ui.MallDetailsActivity;
import com.sikao.app.ui.NoticeActivity;
import com.sikao.app.ui.ReleaseGoodsActivity;
import com.sikao.app.ui.ReleaseTenderActivity;
import com.sikao.app.ui.TenderDetailsActivity;
import com.sikao.app.ui.WebviewActivity;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.NetWorkUtil;
import com.sikao.app.utils.Utils;

import java.util.List;
import java.util.Random;

import static com.sikao.app.ui.TenderDetailsActivity.tenderDetailsActivity;

/**
 * 首页
 */
public class Fragment1 extends BaseFragment implements View.OnClickListener, BaseSliderView.OnSliderClickListener {


    private View rootView;//缓存Fragment view
    private SliderLayout mSliderLayout;

    private Banner mBanner;
    private MallListModel mallListModel;
    private TenderListModel tenderListModel;
    private PurchaseAdapter purchaseAdapter;
    private SupplyAdapter supplyAdapter;
    private List<TenderBean.ResBean.ListBean> purchaseBeans;
    private List<MallBean.ResBean.ListBean> supplyBeans;
    private GetListSubmitBean getListSubmitBean;

    private ImageView locationIv;
    private TextView locationTv;
    private LinearLayout noticeLayout;//公告
    private LinearLayout entrustLayout;//委托业务
    private LinearLayout releaseCommodityLayout;//发布商品
    private LinearLayout releaseTenderLayout;//发布招标
    private LinearLayout hotInformationLayout;//热门资讯
    private LinearLayout latestQuotationLayout;//最新行情 合并到热门资讯

    private LinearLayout logisticsLayout;//物流App

    private LinearLayout companyAreaLayout;//企业专区 改名为品牌专区
    private LinearLayout companyPerspectiveLayout;//惠煤观点

    private LinearLayout groupPurchaseLayout;//团购
    private LinearLayout financialLayout;//金融App
    private LinearLayout billLayout;//票据App
    private LinearLayout creditInvestigationLayout;//征信App

    private LinearLayout purchaseMore;
    private ListView purchaseLv;
    private LinearLayout supplyMore;
    private ListView supplyLv;
    private TextView titleTv;

    private LocationService locationService;
    private boolean isLocate;
    private Intent intent;
    private PullToRefreshScrollView mPullRefreshScrollView;
    private boolean isRefresh;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment1, container, false);
        initView(rootView);
        initListener();
        init();
        return rootView;
    }

    @Override
    public void onStart() {
        if (!isLocate) {
            startLocate();
        }
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mSliderLayout.stopAutoCycle();
        super.onDestroy();
    }

    private void initView(View view) {
        mSliderLayout = (SliderLayout) view.findViewById(R.id.slider);
        entrustLayout = (LinearLayout) view.findViewById(R.id.entrust_layout);
        noticeLayout = (LinearLayout) view.findViewById(R.id.notice_layout);
        releaseCommodityLayout = (LinearLayout) view.findViewById(R.id.release_commodity_layout);
        releaseTenderLayout = (LinearLayout) view.findViewById(R.id.release_tender_layout);
        hotInformationLayout = (LinearLayout) view.findViewById(R.id.hot_information_layout);
        latestQuotationLayout = (LinearLayout) view.findViewById(R.id.latest_quotation_layout);
        companyAreaLayout = (LinearLayout) view.findViewById(R.id.company_area_layout);
        companyPerspectiveLayout = (LinearLayout) view.findViewById(R.id.company_perspective_layout);

        logisticsLayout = (LinearLayout) view.findViewById(R.id.logistics_layout);//物流App

        groupPurchaseLayout = (LinearLayout) view.findViewById(R.id.group_purchase_layout);//团购

        financialLayout = (LinearLayout) view.findViewById(R.id.financial_layout);//金融App

        billLayout = (LinearLayout) view.findViewById(R.id.bill_layout);//票据App

        creditInvestigationLayout = (LinearLayout) view.findViewById(R.id.credit_investigation_layout);//征信App


        purchaseMore = (LinearLayout) view.findViewById(R.id.purchase_more);
        supplyMore = (LinearLayout) view.findViewById(R.id.supply_more);
        purchaseLv = (ListView) view.findViewById(R.id.purchase_lv);
        supplyLv = (ListView) view.findViewById(R.id.supply_lv);
        titleTv = (TextView) view.findViewById(R.id.title_middle_tv);
        locationIv = (ImageView) view.findViewById(R.id.title_left_img);
        locationTv = (TextView) view.findViewById(R.id.title_left_tv);
        mPullRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.pull_refresh_scrollview);

    }

    private void initListener() {
        purchaseMore.setOnClickListener(this);
        supplyMore.setOnClickListener(this);
        entrustLayout.setOnClickListener(this);
        noticeLayout.setOnClickListener(this);
        releaseCommodityLayout.setOnClickListener(this);
        releaseTenderLayout.setOnClickListener(this);
        hotInformationLayout.setOnClickListener(this);
        latestQuotationLayout.setOnClickListener(this);
        companyAreaLayout.setOnClickListener(this);
        companyPerspectiveLayout.setOnClickListener(this);


        logisticsLayout.setOnClickListener(this);//物流App

        groupPurchaseLayout.setOnClickListener(this);//团购

        financialLayout.setOnClickListener(this);//金融App

        billLayout.setOnClickListener(this);//票据App

        creditInvestigationLayout.setOnClickListener(this);//征信App


        locationIv.setOnClickListener(this);
        purchaseLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), TenderDetailsActivity.class);
                intent.putExtra("inviteId", purchaseBeans.get(position).getId());
                startActivity(intent);
            }
        });
        supplyLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), MallDetailsActivity.class);
                intent.putExtra("goodsId", supplyBeans.get(position).getId());
                startActivity(intent);
            }
        });
        mPullRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //重新请求
                isRefresh = true;
                startLocate();
                if (mBanner == null) {
                    requestBannerList();
                }
                requestSupplyList(false);
                requestPurchaseList(false);
            }

        });
    }

    private void init() {
        titleTv.setText("惠煤网");
        locationIv.setVisibility(View.VISIBLE);
        getListSubmitBean = new GetListSubmitBean();
        getListSubmitBean.setThisPage("1");
        getListSubmitBean.setPageNum("5");
        requestBannerList();
        requestSupplyList(false);
        requestPurchaseList(true);
        intent = new Intent();
    }

    @Override
    public void onClick(View v) {
        boolean isInstalled = false;//默认没有安装
        ComponentName cn = null;
        switch (v.getId()) {
            case R.id.title_left_img:
                startLocate();
                break;
            case R.id.entrust_layout://委托业务
                intent.setClass(getActivity(), EntrustsActivity.class);
                startActivity(intent);
                break;
            case R.id.notice_layout://公告
                intent.setClass(getActivity(), NoticeActivity.class);
                startActivity(intent);
                break;
            case R.id.hot_information_layout://热门资讯
                intent.setClass(getActivity(), HotInformationActivity.class);
                startActivity(intent);
                break;
            case R.id.latest_quotation_layout://最新行情
                intent.setClass(getActivity(), LatestQuotationActivity.class);
                startActivity(intent);
                break;
            case R.id.company_area_layout://企业专区 改为品牌专区
                intent.setClass(getActivity(), CompanyAreaActivity.class);
                startActivity(intent);
                break;
            case R.id.company_perspective_layout://惠煤观点
                intent.setClass(getActivity(), CompanyPerspectiveActivity.class);
                startActivity(intent);
                break;
            case R.id.release_commodity_layout://发布商品
                if (ConstantClass.state == 0) {
                    intent.setClass(getActivity(), LoginActivity.class);
                    //intent.putExtra("activity", ReleaseGoodsActivity.class.getName());
                } else if (!ConstantClass.isSeller) {
                    intent.setClass(getActivity(), CompanyApplyActivity.class);
                } else {
                    intent.setClass(getActivity(), ReleaseGoodsActivity.class);
                }
                startActivity(intent);
                break;
            case R.id.release_tender_layout://发布招标
                if (ConstantClass.state == 0) {
                    intent.setClass(getActivity(), LoginActivity.class);
                    //intent.putExtra("activity", ReleaseTenderActivity.class.getName());
                } else {
                    intent.setClass(getActivity(), ReleaseTenderActivity.class);
                }
                startActivity(intent);
                break;
            case R.id.purchase_more://招标查看更多
                ((FirstActivity) getActivity()).getTabhost().setCurrentTab(2);
                break;
            case R.id.supply_more://商城查看更多
                ((FirstActivity) getActivity()).getTabhost().setCurrentTab(1);
                break;


            case R.id.logistics_layout://物流App
                isInstalled = isAppInstalled(getActivity(), "com.sikao.app.transport.consignor");

                if (isInstalled) {
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    cn = new ComponentName("com.sikao.app.transport.consignor", "com.sikao.app.ui.MainActivity");
                    intent.setComponent(cn);
                    startActivity(intent);
                } else {
                    Utils.showToast("该应用未安装，请安装后使用");
                }

                break;
            case R.id.group_purchase_layout://团购
                // intent.setClass(getActivity(), GroupBuyActivity.class);
                intent.setClass(getActivity(), WebviewActivity.class);//NewsDetailActivity
                Random random =new Random(100000);
                intent.putExtra("url", HttpApi.BANNERUTL + "api_1/teamBuy/teamlist?idhd="+random.nextInt());

                //   intent.putExtra("url","http://192.168.1.117:8080/qq/2.html?idhd="+random.nextInt());

                startActivity(intent);
                break;
            case R.id.financial_layout://金融App
                isInstalled = isAppInstalled(getActivity(), "com.sikao.app.transport.consignor111");
                if (isInstalled) {
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    cn = new ComponentName("com.sikao.app.transport.consignor", "com.sikao.app.ui.MainActivity");
                    intent.setComponent(cn);
                    startActivity(intent);
                } else {
                    Utils.showToast("该应用未安装，请安装后使用");
                }

                break;
            case R.id.bill_layout://票据App
                isInstalled = isAppInstalled(getActivity(), "com.sikao.app.transport.consignor111");
                if (isInstalled) {
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    cn = new ComponentName("com.sikao.app.transport.consignor", "com.sikao.app.ui.MainActivity");
                    intent.setComponent(cn);
                    startActivity(intent);
                } else {
                    Utils.showToast("该应用未安装，请安装后使用");
                }
                break;
            case R.id.credit_investigation_layout://征信App
                isInstalled = isAppInstalled(getActivity(), "com.sikao.app.transport.consignor111");
                if (isInstalled) {
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    cn = new ComponentName("com.sikao.app.transport.consignor", "com.sikao.app.ui.MainActivity");
                    intent.setComponent(cn);
                    startActivity(intent);
                } else {
                    Utils.showToast("该应用未安装，请安装后使用");
                }
                break;
            default:
                break;
        }
    }

    private void requestSupplyList(boolean isShow) {
        if (!NetWorkUtil.checkNetwork(true)) {
            if (isRefresh) {
                mPullRefreshScrollView.onRefreshComplete();
            }
            return;
        }
        if (mallListModel == null) {
            mallListModel = new MallListModel(getActivity(), new OnNetBackListener<MallBean>() {
                @Override
                public void netBack(MallBean data) {
                    if (isRefresh) {
                        mPullRefreshScrollView.onRefreshComplete();
                    }
                    if (data == null) {
                        return;
                    }
                    if (data.getStatus().equals("1")) {
                        supplyBeans = data.getRes().getList();
                        supplyAdapter = new SupplyAdapter(getActivity(), supplyBeans);
                        supplyLv.setAdapter(supplyAdapter);
                    }
                }
            });
        }
        mallListModel.request(JSONUtil.toJSON(getListSubmitBean), isShow);
    }

    private void requestPurchaseList(boolean isShow) {
        if (!NetWorkUtil.checkNetwork(false)) {
            return;
        }
        if (tenderListModel == null) {
            tenderListModel = new TenderListModel(getActivity(), new OnNetBackListener<TenderBean>() {
                @Override
                public void netBack(TenderBean data) {
                    if (data == null) {
                        return;
                    }
                    if (data.getStatus() == 1) {
                        purchaseBeans = data.getRes().getList();
                        purchaseAdapter = new PurchaseAdapter(getActivity(), purchaseBeans);
                        purchaseLv.setAdapter(purchaseAdapter);
                    }
                }
            });
        }
        tenderListModel.request(JSONUtil.toJSON(getListSubmitBean), isShow);
    }

    private void requestBannerList() {
        if (!NetWorkUtil.checkNetwork(false)) {
            return;
        }
        GetListSubmitBean bean = new GetListSubmitBean();
        bean.setThisPage("1");
        bean.setPageNum("8");
        bean.setType("indexBanner");
        new BannerModel(getActivity(), new OnNetBackListener<Banner>() {
            @Override
            public void netBack(Banner data) {
                if (data == null) {
                    return;
                }
                if (data.getStatus() == 1) {
                    mBanner = data;
                    initSlider();
                } else {
                    Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }).request(JSONUtil.toJSON(bean), false);

    }

    private void initSlider() {
        if (mBanner != null) {
            for (Banner.ResBean banner : mBanner.getRes()) {
                DefaultSliderView sliderView = new DefaultSliderView(this.getActivity());
                sliderView.image(HttpApi.BANNERUTL + banner.getPath())
                        .setScaleType(BaseSliderView.ScaleType.Fit)
                        .setOnSliderClickListener(this);
                mSliderLayout.addSlider(sliderView);
            }
        }
        /*mSliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        PagerIndicator pagerIndicator = mSliderLayout.getPagerIndicator();
		pagerIndicator.setDefaultIndicatorColor(R.color.text_red,R.color.text_black);*/
        mSliderLayout.setPresetTransformer(SliderLayout.Transformer.Default);
        mSliderLayout.setDuration(4000);
        mSliderLayout.startAutoCycle();

    }


    private void startLocate() {
        locationService = ((MyApplication) getActivity().getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                sb.append(location.getTime());
                sb.append("\nerror code : ");
                sb.append(location.getLocType());
                sb.append("\nlatitude : ");
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");
                sb.append(location.getLongitude());
                sb.append("\nradius : ");
                sb.append(location.getRadius());
                sb.append("\nCountryCode : ");
                sb.append(location.getCountryCode());
                sb.append("\nCountry : ");
                sb.append(location.getCountry());
                sb.append("\nDProvince : ");
                sb.append(location.getProvince());
                sb.append("\ncitycode : ");
                sb.append(location.getCityCode());
                sb.append("\ncity : ");
                sb.append(location.getCity());
                if (location.getCity() != null && !location.getCity().equals("null")) {
                    locationService.unregisterListener(mListener); //注销掉监听
                    locationService.stop();
                    locationTv.setText(location.getCity());
                    isLocate = true;
                }
                sb.append("\nDistrict : ");
                sb.append(location.getDistrict());
                sb.append("\nStreet : ");
                sb.append(location.getStreet());
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\nDescribe: ");
                sb.append(location.getLocationDescribe());
                sb.append("\nDirection(not all devices have value): ");
                sb.append(location.getDirection());
                sb.append("\nPoi: ");
                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < location.getPoiList().size(); i++) {
                        Poi poi = location.getPoiList().get(i);
                        sb.append(poi.getName() + ";");
                    }
                }
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 单位：米
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    sb.append("\noperationers : ");
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                //Toast.makeText(getActivity(), sb.toString(), Toast.LENGTH_SHORT).show();
            }
        }

    };

    @Override
    public void onSliderClick(BaseSliderView slider) {
        //Toast.makeText(getActivity(), mSliderLayout.getCurrentPosition() + "", Toast.LENGTH_SHORT).show();
    }

    /* 判断是否安装
    * check the app is installed
    */
    private boolean isAppInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            //System.out.println("没有安装");
            return false;
        } else {
            //System.out.println("已经安装");
            return true;
        }
    }

}
